package com.whj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whj.domain.constants.SystemConstants;
import com.whj.domain.dto.AddCommentDTO;
import com.whj.domain.entity.Comment;
import com.whj.domain.entity.LoginUser;
import com.whj.domain.entity.User;
import com.whj.domain.enums.AppHttpCodeEnum;
import com.whj.domain.response.ResponseResult;
import com.whj.domain.vo.CommentVo;
import com.whj.domain.vo.PageVo;
import com.whj.exception.SystemException;
import com.whj.mapper.CommentMapper;
import com.whj.mapper.UserMapper;
import com.whj.service.CommentService;
import com.whj.service.UserService;
import com.whj.utils.BeanCopyUtils;
import com.whj.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * 评论表(Comment)表服务实现类
 *
 * @author wanghaijun
 * @since 2023-05-25 09:20:20
 */
@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    /**
     * 查询评论信息
     *
     * @param articleId 文章id
     * @param pageNum   分页数量
     * @param pageSize  分页大小
     * @return
     */
    @Override
    public ResponseResult commentList(String commentType, Long articleId, Integer pageNum, Integer pageSize) {

        // 查询文章对应的根评论
        // 对articleId 进行判断
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemConstants.ARTICLE_COMMENT.equals(commentType), Comment::getArticleId, articleId);
        //根评论rootId = -1
        queryWrapper.eq(Comment::getRootId, SystemConstants.COMMENT_ROOT_ID);
        // 评论类型
        queryWrapper.eq(Comment::getType, commentType);

        // 分页查询
        Page<Comment> page = new Page<>(pageNum, pageSize);
        page(page, queryWrapper);
        //bean 拷贝
        List<CommentVo> commentVoList = toCommentList(page.getRecords());

        // 查询所有根评论对应的子评论集合，并赋值给对应的属性
        for (CommentVo commentVo : commentVoList) {
            //查询对应的子评论
            List<CommentVo> children = getChildren(commentVo.getId());
            //赋值
            commentVo.setChildren(children);
        }

        return ResponseResult.okResult(new PageVo(commentVoList, page.getTotal()));
    }

    /**
     * 用户发表评论
     *
     * @param addCommentDTO
     * @return
     */
    @Override
    public ResponseResult addComment(AddCommentDTO addCommentDTO) {

        if (!StringUtils.hasText(addCommentDTO.getContent())) {
            throw new SystemException(AppHttpCodeEnum.CONTENT_NOT_NULL);
        }
        LoginUser loginUser;
        try {
            loginUser = SecurityUtils.getLoginUser();
        } catch (Exception e) {
            throw new InsufficientAuthenticationException(AppHttpCodeEnum.NEED_LOGIN.getMsg());
        }

        Long id = loginUser.getUser().getId();
        addCommentDTO.setCreateBy(id);
        Comment comment = BeanCopyUtils.copyBean(addCommentDTO, Comment.class);
        save(comment);
        return ResponseResult.okResult();
    }

    /**
     * 根据根评论的id查询对应的子评论
     *
     * @param id 根评论id
     * @return 返回子评论集合
     */
    private List<CommentVo> getChildren(Long id) {

        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getRootId, id);
        queryWrapper.orderByAsc(Comment::getCreateTime);
        // 查询
        List<Comment> list = list(queryWrapper);
        List<CommentVo> commentVos = toCommentList(list);
        return commentVos;
    }


    @Autowired
    private UserService userService;

    /**
     * 将文章对应的值copy 并返回 主要针对 Username ToCommentUserName
     *
     * @param list
     * @return
     */
    private List<CommentVo> toCommentList(List<Comment> list) {
        List<CommentVo> copyBeanLists = BeanCopyUtils.copyBeanList(list, CommentVo.class);
        for (CommentVo copyBeanList : copyBeanLists) {
            User user = userService.getById(copyBeanList.getCreateBy());
            if (Objects.isNull(user)){
                break;
            }
            String nickName = user.getNickName();
            copyBeanList.setUsername(nickName);
            //通过toCommentUserId查询用户的昵称并赋值
            //如果toCommentUserId不为-1才进行查询
            if (copyBeanList.getToCommentUserId() != -1) {
                String commentNickName = userService.getById(copyBeanList.getToCommentUserId()).getNickName();
                copyBeanList.setToCommentUserName(commentNickName);
            }
        }
        return copyBeanLists;
    }
}
